import styles from './chart.module.css';
import { PieChart, Pie, Legend } from '@visactor/react-vchart';
import { useState, useRef, useEffect } from 'react';

// const propsData = [ // debug
//   { type: 'oxygen', value: '46.60' },
//   { type: 'silicon', value: '27.72' },
//   { type: 'aluminum', value: '8.13' },
//   { type: 'iron', value: '5' },
//   { type: 'calcium', value: '3.63' },
//   { type: 'sodium', value: '2.83' },
//   { type: 'potassium', value: '2.59' },
//   { type: 'others', value: '3.5' }
// ];

const PieChartCard = ({props}) => {
  const chartRef = useRef(null);
  const [data, setData] = useState([]);

  useEffect(() => {
      setData(props);
  }, [props]);

  useEffect(() => {
    window['vchart'] = chartRef;
  }, []);
  const handlePieClick = params => {
    console.log(params);
  };

  const handleLegendItemClick = params => {
    console.log(params);
  };

  return (
     <div className={`${styles.chartCard} ${styles.square}`}>
        <PieChart
            ref={chartRef}
            data={[{ id: 'id0', values: data }]}
            onLegendItemClick={handleLegendItemClick}
            tooltip={{
              mark: {
                content: [
                  {
                    key: datum => datum['type'],
                    value: datum => datum['value'] + '%'
                  }
                ]
              }
            }}
        >
            <Pie
                categoryField="type"
                valueField="value"
                outerRadius={0.8}
                innerRadius={0.5}
                padAngle={0.6}
                pie={{
                  style: {cornerRadius: 10},
                  state: {
                    hover: {
                      outerRadius: 0.85,
                      lineWidth: 1
                    }
                  }
                }}
                label={{
                  visible: true,
                  formatMethod: (label, data) => {
                    return {
                      type: 'rich',
                      text: [
                        {
                          text: `${data.value}%\n`,
                          fill: 'rgba(0, 0, 0, 0.92)',
                          fontSize: 16,
                          fontWeight: 500,
                          stroke: false
                        },
                        {
                          text: data.type,
                          fill: 'rgba(0, 0, 0, 0.55)',
                          fontSize: 12,
                          fontWeight: 400,
                          stroke: false
                        }
                      ]
                    };
                  },
                  style: {
                    disableAutoWrapLine: true
                  }
                }}
                onClick={handlePieClick}

            />
            <Legend visible orient="top" height={50} />
        </PieChart>
    </div>
  );
};

export default PieChartCard;

